import Vue from 'vue'
import Vuex from 'vuex'
import { getToken } from '@/utils/auth' // getToken from cookie
import { findFriendBelonging } from '@/api/friendlist/friendList'
import { findGroupBelonging } from '@/api/group'
import { pushGroupMessage, pushMessage, sendMessage } from '@/utils/messageUtil'

const defaultSettings = require('../utils/common')

Vue.use(Vuex)

// 获取当前时间
const now = new Date()
const state = {
  // 输入的搜索值
  searchText: '',
  searchGroupText: '',
  // 当前登录用户
  user: {},
  token: getToken(),
  roles: [],
  defaultFriend: defaultSettings.defaultFriend,
  // 私聊聊天列表
  chatList: [],
  // 群列表
  groupList: [],
  // 好友列表
  friendList: [],
  // emoji表情
  emojis: defaultSettings.emojis,
  // 得知当前选择的是哪个对话索引
  selectId: 1,
  // 得知当前选择的是哪个群聊索引
  selectGroupIndex: 0,
  // 得知当前选择的是哪个好友索引
  selectFriendIndex: 0,
  // 维护一个群聊聊天记录
  messages: new Map(),
  // 当前选择的群id
  selectedGroupId: '0'
}

const mutations = {
  // 初始化数据, 好友、群列表从接口请求获取, 聊天列表从本地缓存获取 (session级别, 即浏览器关闭数据会丢失)
  initData(state) {
    debugger
    // 获取好友列表
    findFriendBelonging(state.user.userId).then((res) => {
      const data = res.data
      if (data.length > 0) {
        state.friendList = data
      }
      state.friendList.unshift(this.state.defaultFriend)
    })
    // 获取群列表
    findGroupBelonging(state.user.userId).then((res) => {
      const data = res.data
      if (data.length < 1) {
        return
      }
      state.groupList = data
      // data[0].groupInfo.groupId
      // let map = new Map(Object.entries(this.state.messages))
      for (const i in data) {
        this.state.messages.set(data[i].groupInfo.groupId, defaultSettings.defaultMessage)
      }
      // this.state.messages = map
    })
    // 获取聊天列表
    const data = sessionStorage.getItem('vue-chat')
    if (data || state.chatList.length < 1) {
      state.chatList.unshift(defaultSettings.defaultChat)
    } else {
      state.chatList = JSON.parse(data)
    }
  },

  // 获取搜索值
  search(state, value) {
    state.searchText = value
  },
  // 得知用户当前选择的是哪个对话。便于匹配对应的对话框
  selectSession(state, value) {
    state.selectId = value
  },
  // 得知用户当前选择的是哪个好友。
  selectFriend(state, value) {
    state.selectFriendIndex = value
  },

  /** ********************************* 群聊操作 ****************************************/
  // 获取搜索值
  searchGroup(state, value) {
    state.searchGroupText = value
  },
  // 得知用户当前选择的是哪个对话。便于匹配对应的对话框
  selectSessionGroup(state, value) {
    state.selectGroupIndex = value
  },
  // 得知用户选择的是哪个群聊
  selectGroupId(state, value) {
    state.selectedGroupId = value
  },

  // 保存群聊消息
  sendGroupMessage(state, msg) {
    pushGroupMessage(state, msg)
  },

  // 保存私聊消息
  sendMessage(state, msg) {
    pushMessage(state, msg)
  },

  SET_USER(state, user) {
    state.user = user
  },
  SET_TOKEN(state, token) {
    state.token = token
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },

  send(state) {
    sendMessage(state)
  }
}

function getCurrentState() {
  return state
}

const getters = {
  roles: state => state.roles,
  user: state => state.user,

  // 筛选出含有搜索值的聊天列表
  searchedChatList(state) {
    debugger
    const sessions = state.chatList.filter(sessions => sessions.user.username.includes(state.searchText))
    return sessions
  },
  // 筛选出含有搜索值的好友列表, 搜索按照备注查找匹配好友
  searchedFriendList(state) {
    debugger
    const friends = state.friendList.filter(friends => friends.remark.includes(state.searchText))
      .filter(currentUser => currentUser.id !== state.user.id)
    return friends.length < 1 ? state.defaultFriend : friends
  },
  // 通过当前选择是哪个对话匹配相应的对话
  selectedChat(state) {
    debugger
    const session = state.chatList.find(session => session.id === state.selectId)
    return session
  },
  // 通过当前选择是哪个好友匹配相应的好友
  selectedFriend(state) {
    debugger
    const friend = state.friendList.find(friend => friend.id === state.selectFriendIndex)
    return friend === undefined ? state.defaultFriend[0] : friend
  },
  messages(state) {
    debugger
    const session = state.chatList.find(session => session.id === state.selectId)
    return session.messages
  },

  /** ******************************* 群聊操作 *****************************************/

  // 筛选出含有搜索值的群聊列表
  searchedGroupChatList(state) {
    debugger
    const sessions = state.groupList.filter(sessions => sessions.groupInfo.groupName.includes(state.searchGroupText))
    return sessions
  },
  // 通过当前选择是哪个对话匹配相应的对话
  selectedGroupChat(state) {
    debugger
    const session = state.groupList.find(session => session.id === state.selectGroupIndex)
    if (session) {
      state.selectedGroupId = session.groupInfo.groupId
    }
    return session
  },
  messagesGroup(state) {
    debugger
    return state.messages.get(state.selectedGroupId)
  }
}

const actions = {
  search: ({ commit }, value) => {
    setTimeout(() => {
      commit('search', value)
    }, 1000)
  },
  searchGroup: ({ commit }, value) => {
    setTimeout(() => {
      commit('searchGroup', value)
    }, 1000)
  },
  selectSession: ({ commit }, value) => commit('selectSession', value),
  selectFriend: ({ commit }, value) => commit('selectFriend', value),
  sendMessage: ({ commit }, msg) => commit('sendMessage', msg),
  send: ({ commit }) => commit('send'),
  initData: ({ commit }) => commit('initData'),
  SET_USER: ({ commit }, user) => commit('SET_USER', user),
  SET_TOKEN: ({ commit }, token) => commit('SET_TOKEN', token),
  // searchGroup: ({ commit }, value) => commit('searchGroup', value),
  selectSessionGroup: ({ commit }, value) => commit('selectSessionGroup', value),
  sendGroupMessage: ({ commit }, msg) => commit('sendGroupMessage', msg),
  selectGroupId: ({ commit }, msg) => commit('selectGroupId', msg)
}

// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', true, /\.js$/)

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})

const store = new Vuex.Store({
  modules,
  state,
  mutations,
  getters,
  actions
})

// 监听聊天列表的值， 发生变化就保存在 sessionStorage 中
store.watch(
  (state) => state.chatList,
  (val) => {
    // TODO 存储到 redis
    sessionStorage.setItem('vue-chat', JSON.stringify(val))
  },
  {
    deep: true
  }
)
export default store
export { getCurrentState }

